package com.xinli.business.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xinli.business.domain.*;
import com.xinli.business.service.*;
import com.xinli.common.annotation.RepeatSubmit;
import com.xinli.common.core.controller.BaseController;
import com.xinli.common.core.domain.AjaxResult;
import com.xinli.common.core.page.TableDataInfo;
import com.xinli.common.utils.SecurityUtils;
import com.xinli.common.utils.SendSmsUtil;
import com.xinli.common.utils.StringUtils;
import com.xinli.common.utils.YzCodeUtils;
import com.xinli.pay.wxpay.OrderStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * 我的
 */
@RestController
@RequestMapping("/webApiMy")
public class TWebApiMyController extends BaseController {


    @Autowired
    private ITConfigService tConfigService;


    @Autowired
    private ITGuideService tGuideService;


    @Autowired
    private ITTwxxService tTwxxService;

    @Autowired
    private ITOrderService tOrderService;

    @Autowired
    private YzCodeUtils yzCodeUtils;

    @Autowired
    private IFtMemberService memberService;

    @Autowired
    private ITZxsFollowService tZxsFollowService;

    @Autowired
    private ITQuestionFollowService questionFollowService;


    @Autowired
    private ITQuestionService questionService;


    @Autowired
    private ITOrderRefundService tOrderRefundService;

    @Autowired
    private ITOrderPjService orderPjService;

    @Autowired
    private ILfPostFabulousService postFabulousService;




    /**
     * 我的关注咨询师
     */
    @GetMapping("/getZxsFolllowlist")
    public TableDataInfo getZxsFolllowlist(TZxsFollow tZxsFollow) {
        startPage();
        tZxsFollow.setUserId(SecurityUtils.getUserId()+"");
        List<TZxsFollow> list = tZxsFollowService.selectTZxsFollowList(tZxsFollow);
        return getDataTable(list);
    }

    /**
     * 我的关注问答
     */
    @GetMapping("/getQuestionFolllowlist")
    public TableDataInfo getQuestionFolllowlist(LfPostFabulous postFabulous) {
        startPage();
        postFabulous.setUid(SecurityUtils.getUserId());
        List<LfPostFabulous> tQuestionFollows = postFabulousService.selectLfPostFabulousList(postFabulous);
        return getDataTable(tQuestionFollows);
    }


    /**
     * 关注或取消关注问答
     */
    @PostMapping("/followQuestion")
    public AjaxResult followQuestion(@RequestBody LfPostFabulous postFabulous) {
        Long postId = postFabulous.getPostId();
        Boolean aBoolean = postFabulousService.followQuestion(postId);
        return AjaxResult.success(aBoolean);
    }


    @Autowired
    private ILfCommentThumbsService lfCommentThumbsService;


    /**
     * 点赞评论
     */
    @PostMapping("/followPl/{cid}")
    public AjaxResult followQuestion(@PathVariable("cid") Long cid) {
        Boolean aBoolean = lfCommentThumbsService.followPl(cid);
        return AjaxResult.success(aBoolean);
    }




    /**
     * 关注或取消关注咨询师
     */
    @PostMapping("/followZxs")
    public AjaxResult followZxs(@RequestBody TZxsFollow zxsFollow) {
        String businessId = zxsFollow.getBusinessId();
        if (StringUtils.isEmpty(businessId)) {
            return AjaxResult.error("参数错误");
        }
        Boolean aBoolean = tZxsFollowService.followZxs(businessId);
        return AjaxResult.success(aBoolean);
    }


    /**
     * 修改用户信息
     */
    @RepeatSubmit
    @PostMapping(value = "/updateUserInfo")
    public AjaxResult updateUserInfo(@RequestBody FtMember member) {
        Long userId = SecurityUtils.getUserId();
        member.setMemberId(userId);
        memberService.updateFtMember(member);
        return AjaxResult.success();
    }

    /**
     * 修改用户密码
     */
    @RepeatSubmit
    @PostMapping(value = "/modifyPassWord")
    public AjaxResult modifyPassWord(@RequestBody UpdatePassWord updatePassWord) {
        Long userId = SecurityUtils.getUserId();
        FtMember ftMember = new FtMember();
        ftMember.setMemberId(userId);
        ftMember.setPassword(SecurityUtils.encryptPassword(updatePassWord.getPassword()));
        memberService.updateFtMember(ftMember);
        return AjaxResult.success();
    }


    @Autowired
    private ILfPostService postService;

    @Autowired
    private ILfTopicService  topicService;

    /**
     * 我的提问
     */
    @GetMapping("/getMyQuestionList")
    public TableDataInfo getMyQuestionList(LfPost vo) {
        startPage();
        List<Long> topicIds = topicService.getTopicIds(1);
        vo.setTopicIdArray(topicIds);
        startPage();
        vo.setUid(SecurityUtils.getUserId());
        List<LfPost> list = postService.selectLfPostList(vo);
        for (int i = 0; i < list.size(); i++) {
            postService.setViewAndReplyCountAndReList(list.get(i),"");
        }
        return getDataTable(list);
    }

    /**
     * 我的订单
     */
    @GetMapping("/getMyOrderList")
    public TableDataInfo getMyOrderList(TOrder tOrder) {
        startPage();
        tOrder.setUserId(SecurityUtils.getUserIdStr());
        if("9".equals(tOrder.getOrderStatus())){
            // 待评价
            tOrder.setIsComment("0");
        }else if("10".equals(tOrder.getOrderStatus())){
            // 申述中
            tOrder.setRefundStatus("0");
            tOrder.setOrderStatus("3");
        }else if("3".equals(tOrder.getOrderStatus())){
            // 已完成的订单 不要出现 申诉中的订单
//            tOrder.setNorefundStatus("000000");
        }
        List<TOrder> list = tOrderService.selectTOrderListApp(tOrder);
        return getDataTable(list);
    }




    /**
     * 个人信息
     */
    @GetMapping("/getUserInfo")
    public AjaxResult getUserInfo( ) {
        FtMember member = memberService.selectFtMemberByMemberId(SecurityUtils.getUserId());
        return AjaxResult.success(member);
    }
    /**
     * 我的申诉
     */
    @GetMapping("/getMyOrderRefundList")
    public TableDataInfo getMyOrderRefundList(TOrderRefund refund) {
        startPage();
        refund.setUserId(SecurityUtils.getUserIdStr());
        List<TOrderRefund> list = tOrderRefundService.selectTOrderRefundList(refund);
        return getDataTable(list);
    }


    /**
     * 申述保存
     */
    @Transactional
    @PostMapping("/saveOrderRefund")
    public AjaxResult saveOrderRefund(@RequestBody TOrderRefundVo vo) {
        String orderId = vo.getOrderId();
        TOrder order = tOrderService.selectTOrderById(orderId);
        if (order == null) {
            return AjaxResult.error("订单不存在");
        }
        // 判断订单是否已经有了售后
        QueryWrapper<TOrderRefund> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_id", orderId);
        if (tOrderRefundService.count(queryWrapper) > 0) {
            return AjaxResult.error("订单已经有了售后");
        }
        TOrderRefund orderRefund = new TOrderRefund();
        orderRefund.setOrderId(orderId);
        orderRefund.setOrderNo(order.getOrderNo());
        orderRefund.setUserId(order.getUserId());
        orderRefund.setZxsId(order.getZxsId());
        orderRefund.setTotalAmount(order.getTotalPrice());
        orderRefund.setCheckStatus("1");
        orderRefund.setRefundStatus("0");
        orderRefund.setApplyTime(new Date());
        orderRefund.setBuyerReason(vo.getBuyerReason());
        tOrderRefundService.save(orderRefund);
        order.setRefundStatus("0");
        tOrderService.updateById(order);
        return AjaxResult.success();
    }


    /**
     * 完成订单
     */
    @PostMapping("/finishOrder")
    @RepeatSubmit
    public AjaxResult finishOrder(@RequestBody TOrder vo) {
        TOrder order = tOrderService.selectTOrderById(vo.getId());
        if(!"2".equals(order.getOrderStatus())){
            return AjaxResult.error("订单状态错误");
        }
        order.setFinallyTime(new Date());
        order.setOrderStatus("3");
        tOrderService.updateTOrder(order);
        return  AjaxResult.success();
    }


    /**
     *
     *取消订单
     */
    @RepeatSubmit
    @PostMapping("/cancleOrder")
    public AjaxResult cancleOrder(@RequestBody TOrder vo) {
        TOrder order = tOrderService.selectTOrderById(vo.getId());
        if(!"1".equals(order.getOrderStatus()) &&  !"2".equals(order.getOrderStatus())   ){
            return AjaxResult.error("订单状态错误");
        }
        order.setCancelTime(new Date());
        order.setOrderStatus("4");
        order.setCloseType("4");
        tOrderService.updateTOrder(order);
        return  AjaxResult.success();
    }

    /**
     * 获取订单详细信息
     */
    @GetMapping(value = "/orderDetail/{id}")
    public AjaxResult orderDetail(@PathVariable("id") String id) {
        TOrder order = tOrderService.selectTOrderById(id);
        return AjaxResult.success(order);
    }

    /**
     * 评价
     */
    @RepeatSubmit
    @PostMapping("/saveOrderPj")
    @Transactional
    public AjaxResult saveOrderPj(@RequestBody TOrderPj vo) {
        String orderId = vo.getOrderId();
        TOrder order = tOrderService.selectTOrderById(orderId);
        if (order == null) {
            return AjaxResult.error("订单不存在");
        }
        if ("1".equals(order.getIsComment())) {
            return AjaxResult.error("订单已经评价过了");
        }
        // 只能针对已完成的评价
        if (!"3".equals(order.getOrderStatus())) {
            return AjaxResult.error("订单状态不对，不能评价");
        }
        TOrderPj orderPj = new TOrderPj();
        orderPj.setOrderId(orderId);
        orderPj.setOrderNo(order.getOrderNo());
        orderPj.setUserId(SecurityUtils.getUserIdStr());
        orderPj.setZxsId(order.getZxsId());
        orderPj.setContent(vo.getContent());
        orderPj.setStatus("1");
        orderPjService.save(orderPj);
        order.setIsComment("1");
        tOrderService.updateById(order);
        return  AjaxResult.success();
    }



}
